"""
    装饰器：用来校验用户的登录状态
"""
import json

import jwt
from django.http import JsonResponse

from dashopt import settings
from users.models import UserProfile


def logging_check(func):
    def wrapper(self, request, *args, **kwargs):
        """
        token 校验逻辑
        1.获取token
        2.校验token
            2.1失败：直接返回
            2.2成功：执行视图func(...)
        """
        # token在请求头中
        # Django会把请求头大写，并且加上HTTP_前缀
        # request.META:{"":"","":""}
        token = request.META.get(
            "HTTP_AUTHORIZATION")
        try:
            payload = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms="HS256")
        except Exception as e:
            # token 有问题 直接返回
            return JsonResponse({'code': 403})

        #封装myuser属性
        username = payload.get("username")
        user = UserProfile.objects.get(username = username)
        request.my_user = user
        # 封装mydata属性
        request_data = request.body
        if request_data:
            request.my_data = json.loads(request_data)
        # 走视图函数
        return func(self, request, *args, **kwargs)

    return wrapper

